//
//  BMSRealnamePopupView.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

#import "BMSRealnamePopupView.h"
#import <Masonry/Masonry.h>
#import "BMSToastManager.h"
#import "BMSPopupQueueManager.h"
#import "BMSAPIService.h"
#import "BMSInitializer.h"
#import "BMSRealnameResultModel.h"
#import "BMSOnlineSessionManager.h"
#import "BMSAntiAddictionManager.h"
#import "BMSAntiAddictionPopupView.h"
#import "BMSPrivate.h"

@interface BMSRealnamePopupView () <UITextFieldDelegate>
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UITextField *nameField;
@property (nonatomic, strong) UITextField *idField;
@property (nonatomic, strong) UILabel *nameErrorLabel;
@property (nonatomic, strong) UILabel *idErrorLabel;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) UIButton *cancelButton;
@end


static CGFloat lastKeyboardHeight = 0;

@implementation BMSRealnamePopupView

- (instancetype)init {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        [self setupViews];
        self.userInteractionEnabled = YES;
        _contentView.userInteractionEnabled = YES;
        // 添加手势关闭键盘
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBackground)];
        tap.cancelsTouchesInView = NO;
        [self addGestureRecognizer:tap];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillChangeFrame:)
                                                     name:UIKeyboardWillChangeFrameNotification
                                                   object:nil];
    }
    [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_REALNAME_INFO_SHOW description:BMS_WDS_REALNAME_POPUP_SHOW tab1:@"" tab2:@"" tab3:@"" tabN:@{}]];
    return self;
}

- (void)setupViews {
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = UIColor.whiteColor;
    _contentView.layer.cornerRadius = 12;
    [self addSubview:_contentView];

    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.greaterThanOrEqualTo(@280);
        make.width.lessThanOrEqualTo(self).multipliedBy(0.9);
        make.width.lessThanOrEqualTo(@400);
        make.height.lessThanOrEqualTo(self).multipliedBy(0.95);
    }];

    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = @"实名认证";
    _titleLabel.textColor = UIColor.whiteColor;
    _titleLabel.backgroundColor = UIColor.systemBlueColor;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [_contentView addSubview:_titleLabel];

    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(_contentView);
        make.height.mas_equalTo(44);
    }];

    _tipLabel = [[UILabel alloc] init];
    _tipLabel.numberOfLines = 0;
    _tipLabel.font = [UIFont systemFontOfSize:14];
    _tipLabel.textColor = UIColor.blackColor;
    _tipLabel.text =
    @"尊敬的玩家：\n"
    "根据国家新闻出版署《关于防止未成年人沉迷网络游戏的通知》要求，请完成实名认证。\n"
    "您提供的信息仅用于验证身份，我们将严格保障您的隐私安全，不会向任何第三方机构或个人泄露。";
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 4;

    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:_tipLabel.text attributes:@{
        NSFontAttributeName: [UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName: UIColor.blackColor,
        NSParagraphStyleAttributeName: style
    }];
    _tipLabel.attributedText = attrText;
    [_contentView addSubview:_tipLabel];

    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLabel.mas_bottom).offset(12);
        make.left.right.equalTo(_contentView).insets(UIEdgeInsetsMake(0, 16, 0, 16));
    }];

    _nameField = [[UITextField alloc] init];
    _nameField.placeholder = @"真实姓名";
    _nameField.borderStyle = UITextBorderStyleRoundedRect;
    [_contentView addSubview:_nameField];

    _nameErrorLabel = [[UILabel alloc] init];
    _nameErrorLabel.textColor = UIColor.redColor;
    _nameErrorLabel.font = [UIFont systemFontOfSize:12];
    _nameErrorLabel.hidden = YES;
    [_contentView addSubview:_nameErrorLabel];

    _idField = [[UITextField alloc] init];
    _idField.placeholder = @"身份证号";
    _idField.borderStyle = UITextBorderStyleRoundedRect;
    [_contentView addSubview:_idField];

    _idErrorLabel = [[UILabel alloc] init];
    _idErrorLabel.textColor = UIColor.redColor;
    _idErrorLabel.font = [UIFont systemFontOfSize:12];
    _idErrorLabel.hidden = YES;
    [_contentView addSubview:_idErrorLabel];

    [_nameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tipLabel.mas_bottom).offset(12);
        make.left.right.equalTo(_tipLabel);
        make.height.mas_equalTo(40);
    }];

    [_nameErrorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nameField.mas_bottom).offset(4);
        make.left.right.equalTo(_nameField);
    }];

    [_idField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nameErrorLabel.mas_bottom).offset(8);
        make.left.right.height.equalTo(_nameField);
    }];

    [_idErrorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_idField.mas_bottom).offset(4);
        make.left.right.equalTo(_idField);
    }];

    UILabel *desc = [[UILabel alloc] init];
    desc.text = @"认证完成后 解锁完整游戏权限";
    desc.font = [UIFont systemFontOfSize:12];
    desc.textColor = UIColor.systemBlueColor;
    desc.textAlignment = NSTextAlignmentCenter;
    [_contentView addSubview:desc];

    [desc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_idErrorLabel.mas_bottom).offset(10);
        make.left.right.equalTo(_idField);
    }];

    _confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_confirmButton setTitle:@"立即认证" forState:UIControlStateNormal];
    _confirmButton.backgroundColor = UIColor.systemBlueColor;
    [_confirmButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    _confirmButton.layer.cornerRadius = 6;
    [_confirmButton addTarget:self action:@selector(onConfirmPressed) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_confirmButton];

    _cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_cancelButton setTitle:@"稍后处理" forState:UIControlStateNormal];
    [_cancelButton setTitleColor:UIColor.grayColor forState:UIControlStateNormal];
    _cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_cancelButton addTarget:self action:@selector(onCancelPressed) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_cancelButton];
    _cancelButton.hidden = self.forceRealname;
    _cancelButton.hidden = [self isShowRnNoAuthBtn];

    [_confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(desc.mas_bottom).offset(12);
        make.left.right.equalTo(desc);
        make.height.mas_equalTo(44);
    }];

    [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_confirmButton.mas_bottom).offset(8);
        make.centerX.equalTo(_confirmButton);
        make.bottom.equalTo(_contentView.mas_bottom).offset(-16);
    }];
}

- (void)onConfirmPressed {
    [self showValidationErrorWithMessage:@"" forField:@"name"];
    [self showValidationErrorWithMessage:@"" forField:@"id"];

    BOOL valid = YES;
    if (self.nameField.text.length == 0) {
        [self showValidationErrorWithMessage:@"请输入真实姓名" forField:@"name"];
        valid = NO;
    }
    if (self.idField.text.length == 0) {
        [self showValidationErrorWithMessage:@"请输入身份证号" forField:@"id"];
        valid = NO;
    }
    if (self.idField.text.length > 0 && self.idField.text.length != 18) {
        [self showValidationErrorWithMessage:@"身份证号格式错误" forField:@"id"];
        [BMSToastManager showToast:@"身份证号错误"];
        valid = NO;
    }

    if (!valid) return;

    // ✅ 接口请求
    [BMSAPIService submitRealnameWithName:self.nameField.text
                                   idCard:self.idField.text
                                zxbAppId:@""
                                  success:^(NSDictionary *response) {
        int code = [response[@"code"] intValue];
        if (code == 0) {
            NSDictionary *responseDict = response[@"data"];
            BMSRealnameResultModel *result = [BMSRealnameResultModel modelWithDictionary:responseDict];

            BOOL isTeenager = [self isTeenagerWithBirthday:result.birthday];
            [[BMSInitializer shared] markRealnameVerified:isTeenager];

            if ([result.res isEqualToString:@"1"]) {
                
                [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_REALNAME_VERIFY_SUCCESS description:BMS_WDS_REALNAME_VERIFY_SUCCESS tab1:@"" tab2:@"" tab3:@"" tabN:@{}]];
                
                [BMSToastManager showToast:@"实名认证成功"];
                
                [BMSInitializer shared].isTeenager = isTeenager;
                if (isTeenager) {
                    [self handleAntiAddictionIfNeeded];
                }
                NSLog(isTeenager ? @"🚫 用户未成年" : @"✅ 用户已成年");
                [self dismiss];
                [[BMSPopupQueueManager sharedManager] dismissCurrentPopup];
                

                if (self.onResult) {
                    self.onResult(YES, nil);
                }
            } else {
                [BMSToastManager showToast:@"身份信息不匹配"];
            }
        } else {
            NSLog(@"实名认证失败：%@", response);
            [BMSToastManager showToast:response[@"msg"] ?: @"实名认证失败"];
            if (self.onResult) {
                NSError *failError = [NSError errorWithDomain:@"bms.realname"
                                                         code:1002
                                                     userInfo:@{NSLocalizedDescriptionKey: @"实名认证失败"}];
                [BMSInitializer shared].isTeenager = isTeenager;

//                self.onResult(NO, failError);
                
            }
        }

    } failure:^(NSError *error) {
        [BMSToastManager showToast:error.localizedDescription ?: @"实名认证失败"];
        if (self.onResult) {
            NSError *failError = [NSError errorWithDomain:@"bms.realname"
                                                     code:1002
                                                 userInfo:@{NSLocalizedDescriptionKey: @"实名认证失败"}];
            self.onResult(NO, failError);
        }
    }];
    
    [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_REALNAME_INFO_CLICK description:BMS_WDS_REALNAME_POPUP_ACTION tab1:@"" tab2:@"" tab3:@"" tabN:@{}]];
}

- (void)showValidationErrorWithMessage:(NSString *)message forField:(NSString *)fieldKey {
    if ([fieldKey isEqualToString:@"name"]) {
        self.nameErrorLabel.text = message;
        self.nameErrorLabel.hidden = (message.length == 0);
    } else if ([fieldKey isEqualToString:@"id"]) {
        self.idErrorLabel.text = message;
        self.idErrorLabel.hidden = (message.length == 0);
    }
}

- (void)onCancelPressed {
    if (self.onResult) {
        NSError *cancelError = [NSError errorWithDomain:@"bms.realname"
                                                   code:1001
                                               userInfo:@{NSLocalizedDescriptionKey: @"用户取消认证"}];
        self.onResult(NO, cancelError);
    }

    [[BMSPopupQueueManager sharedManager] dismissCurrentPopupWithCompletion:^{
        [[BMSOnlineSessionManager shared] startTracking];

        [BMSOnlineSessionManager shared].onTickCheck = ^(NSTimeInterval totalSeconds) {
            if (totalSeconds >= 3600 &&
                ![BMSInitializer shared].didRealnameAuth &&
                ![BMSInitializer shared].hasShownForcedRealnamePopup) {
                
                [BMSInitializer shared].hasShownForcedRealnamePopup = YES;

                BMSRealnamePopupView *popup = [[BMSRealnamePopupView alloc] init];
                popup.forceRealname = YES;
                popup.cancelButton.hidden = YES; // ✅ 隐藏按钮

                [[BMSPopupQueueManager sharedManager] presentPopup:popup];
            }
        };
    }];
}

- (void)showInView:(UIView *)parentView {
    UIView *target = parentView ?: UIApplication.sharedApplication.keyWindow;
    [target addSubview:self];
    self.alpha = 0;
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 1.0;
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)handleTapBackground {
    [self endEditing:YES];
    // 弹窗恢复原位
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark ------ NSNotification --------------

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationOptions curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16;

    CGFloat screenHeight = UIScreen.mainScreen.bounds.size.height;
    CGFloat keyboardHeight = screenHeight - endFrame.origin.y;

    if (fabs(lastKeyboardHeight - keyboardHeight) < 1.0) {
        return; // 键盘高度没变，不处理
    }
    lastKeyboardHeight = keyboardHeight;

    CGFloat contentBottomY = CGRectGetMaxY(self.contentView.frame);
    CGFloat overlap = MAX(0, contentBottomY + keyboardHeight - screenHeight + 20);

    [UIView animateWithDuration:duration delay:0 options:curve animations:^{
        self.contentView.transform = CGAffineTransformMakeTranslation(0, -overlap);
    } completion:nil];
}

#pragma mark ------- private method ----------

- (BOOL)isTeenagerWithBirthday:(NSString *)birthday {
    if (birthday.length != 8) return YES; // 日期格式不合法，默认为未成年

    NSInteger year = [[birthday substringToIndex:4] integerValue];
    NSInteger month = [[birthday substringWithRange:NSMakeRange(4, 2)] integerValue];
    NSInteger day = [[birthday substringFromIndex:6] integerValue];

    NSDateComponents *birthComponents = [[NSDateComponents alloc] init];
    birthComponents.year = year;
    birthComponents.month = month;
    birthComponents.day = day;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *birthDate = [calendar dateFromComponents:birthComponents];
    if (!birthDate) return YES;

    NSDate *now = [NSDate date];
    NSDateComponents *diff = [calendar components:NSCalendarUnitYear fromDate:birthDate toDate:now options:0];
    return diff.year < 18;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"点击 %@",[self class]);
}

- (BOOL)isShowRnNoAuthBtn {
    BOOL rnNoAuthBtn = ![BMSInitializer shared].launchModel.rnNoAuthBtn;
    return rnNoAuthBtn;
}

- (void)handleAntiAddictionIfNeeded {
    [BMSAntiAddictionPopupView showWarningPopup];
}

@end
